package com.huawei.hmsdemo10086.Adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huawei.hmsdemo10086.Activity.CarActivity;
import com.huawei.hmsdemo10086.BuildConfig;
import com.huawei.hmsdemo10086.POJO.Car;
import com.huawei.hmsdemo10086.POJO.Goods;
import com.huawei.hmsdemo10086.POJO.Order;
import com.huawei.hmsdemo10086.POJO.Result;
import com.huawei.hmsdemo10086.R;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CarAdapter extends BaseAdapter {

    private List<Car> datas = new ArrayList<Car>();
    private Context context;
    private LayoutInflater layoutInflater;
    private List<Car> choosed_data = new ArrayList<Car>();

    public List<Car> getChoosed_data() {
        return choosed_data;
    }

    public void clear_data()
    {
        choosed_data.clear();
    }

    public CarAdapter(Context context, List<Car> datas) {
        this.datas = datas;
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return datas.size(); //返回列表的长度
    }

    @Override
    public Car getItem(int position) {
        return datas.get(position); //通过列表的位置 获得集合中的对象
    }

    @Override
    public long getItemId(int position) { // 获得集合的Item的位置
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.car_node, null);//找到布局文件
            convertView.setTag(new ViewHolder(convertView));
        }
        initViews(getItem(position), (ViewHolder) convertView.getTag());
        return convertView;

    }

    private void initViews(Car data, ViewHolder holder) {//初始化数据


        holder.num.setText(""+data.getNum());//设置Tag

        //设置新闻标题为集合中获得的标题
        holder.title.setText(data.getGoods().getName());

        //Glide设置图片圆角角度
        RoundedCorners roundedCorners = new RoundedCorners(10);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(20, 20);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);

        Glide.with(context).load(data.getGoods().getPicaddress())
                .apply(options)
                .into(holder.img);

        holder.price.setText(""+data.getGoods().getPrice() * data.getNum());

        holder.btnDecrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(data.getNum()>1){
                    String url = "http://10.0.2.2:8443/api/updateNum";
                    OkHttpClient mOkHttpClient = new OkHttpClient();

                    String json = "{\n" +
                            "  \"userid\": \"" + data.getUserid() + "\",\n" +
                            "  \"num\": \"" + (data.getNum()-1) + "\",\n" +
                            "  \"goodsid\": \"" + data.getGoodsid() + "\"\n" +
                            "}";
                    Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                    mOkHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("测试", e+"");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            data.setNum(data.getNum()-1);
                            holder.num.setText(""+data.getNum());
                        }
                    });
//                    num--;
//                    etAmount.setText(String.valueOf(num));
                }

            }
        });
        holder.btnIncrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("1111");
                if(data.getNum() < data.getGoods().getNum())
                {
                    String url = "http://10.0.2.2:8443/api/updateNum";
                    OkHttpClient mOkHttpClient = new OkHttpClient();

                    String json = "{\n" +
                            "  \"userid\": \"" + data.getUserid() + "\",\n" +
                            "  \"num\": \"" + (data.getNum()+1) + "\",\n" +
                            "  \"goodsid\": \"" + data.getGoodsid() + "\"\n" +
                            "}";
                    Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                    mOkHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("测试", e+"");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            data.setNum(data.getNum()+1);
                            holder.num.setText(""+data.getNum());
                        }
                    });
//                    num++;
//                    etAmount.setText(String.valueOf(num));
                }

            }
        });


        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    choosed_data.add(data);

                }else{
                    choosed_data.remove(data);
                }
            }
        });


        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://10.0.2.2:8443/api/removeFromCar";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                String json = "{\n" +
                        "  \"goodsid\": \"" + data.getGoodsid() + "\",\n" +
                        "  \"userid\": \"" + data.getUserid() + "\"\n" +
                        "}";


                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {



                    }
                });
                choosed_data.remove(data);
                datas.remove(data);
                notifyDataSetChanged();

            }


        });



    }

    protected class ViewHolder {
        private TextView price;
        private TextView title;
        private TextView num;
        private Button delete;
        private CheckBox checkBox;
        private ImageView img;
        private Button btnDecrease;
        private Button btnIncrease;

        public ViewHolder(View view) {
            title = (TextView) view.findViewById(R.id.goods_title);
            num = (TextView) view.findViewById(R.id.goods_num);
            price = (TextView) view.findViewById(R.id.goods_price);
            delete = (Button)view.findViewById(R.id.delete);
            checkBox = (CheckBox)view.findViewById(R.id.choose_goods);
            img = view.findViewById(R.id.car_img);
            btnDecrease = (Button)view.findViewById(R.id.btnDecrease);
            btnIncrease = (Button)view.findViewById(R.id.btnIncrease);
        }
    }

}
